import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import prisma from '@/lib/prisma'

export async function GET(request: NextRequest, { params }: { params: { id: string } }) {
  try {
    const session = await getServerSession(authOptions)
    if (!session?.user) {
      return NextResponse.json({ message: '未授权' }, { status: 401 })
    }

    // Only students can access their own history for now
    // Teachers/Admins might have a different view or access through another endpoint
    if (session.user.role !== 'STUDENT') {
      return NextResponse.json({ message: '权限不足' }, { status: 403 })
    }

    const experimentId = params.id
    const studentIdFromQuery = request.nextUrl.searchParams.get('studentId')

    if (!studentIdFromQuery) {
        return NextResponse.json({ message: '缺少 studentId 参数' }, { status: 400 });
    }

    // Ensure students can only fetch their own history
    if (session.user.id !== studentIdFromQuery) {
        return NextResponse.json({ message: '无权访问此学生的历史记录' }, { status: 403 });
    }

    const history = await prisma.submission.findMany({
      where: {
        experimentId: experimentId,
        userId: studentIdFromQuery, // Assuming 'userId' links submission to the student
      },
      include: {
        stageSubmissions: {
          include: {
            stage: {
              select: {
                id: true,
                title: true,
                order: true,
                content: true, // Fetch full content initially
                type: true, // <<< --- Added type here
                experiment: { // Need experiment details for end time check
                  select: { endTime: true }
                }
              },
            },
          },
          orderBy: {
            stage: {
              order: 'asc' // Order stages within a submission by their defined order
            }
          }
        },
        // Include user details if needed by frontend, though studentId is already known
        // user: { select: { id:true, name:true, email:true } }
      },
      orderBy: {
        submittedAt: 'desc', // Show most recent submissions first
      },
    })

    // Process history to conditionally include answer explanations and correct answers in stage.content
    const processedHistory = history.map((submission: any) => ({
      ...submission,
      stageSubmissions: submission.stageSubmissions.map((ss: any) => {
        let stageContentForStudent: any = {};
        if (ss.stage.content && typeof ss.stage.content === 'string') {
          try { stageContentForStudent = JSON.parse(ss.stage.content); } catch (e) { console.error('Error parsing stage content in history API', e); }
        } else {
          stageContentForStudent = ss.stage.content || {};
        }
        
        const originalStageContent = { ...stageContentForStudent }; // Keep a copy before modification

        // For history, the main condition is if the teacher marked it as visible.
        // The fact that it's a past submission implies the student has "completed" that attempt.
        const canViewExplanation = originalStageContent.explanationVisibleToStudent === true;
        
        if (!canViewExplanation) {
          if (stageContentForStudent.hasOwnProperty('answerExplanation')) {
            delete stageContentForStudent['answerExplanation'];
          }
          if (stageContentForStudent.hasOwnProperty('correctAnswerId')) {
            delete stageContentForStudent['correctAnswerId'];
          }
          if (stageContentForStudent.hasOwnProperty('standardAnswers')) {
            delete stageContentForStudent['standardAnswers'];
          }
        }
        return {
          ...ss,
          stage: {
            ...ss.stage,
            content: stageContentForStudent, // Return potentially modified content
          }
        };
      })
    }));

    return NextResponse.json({ history: processedHistory })

  } catch (error) {
    console.error('获取实验历史记录失败:', error)
    return NextResponse.json({ message: '获取实验历史记录失败' }, { status: 500 })
  }
} 